package com.skyolder.milkbee.web.rest;

import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.bingoohuang.patchca.service.Captcha;
import com.skyolder.milkbee.dto.SimpleResult;
import com.skyolder.milkbee.tool.CaptchaUtil;

import io.swagger.annotations.ApiParam;


@RestController
@RequestMapping("/")
public class CaptchaResource {
	public static String CAPTCHA="CAPTCHA_LOGIN";
	@GetMapping("/captcha")
	public void captcha(HttpServletResponse response, HttpServletRequest request){
		response.setContentType("image/jpeg");
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		long time = System.currentTimeMillis();
		response.setDateHeader("Last-Modified", time);
		response.setDateHeader("Date", time);
		response.setDateHeader("Expires", time);

		Captcha captcha = CaptchaUtil.getCaptcha();
		String code = captcha.getChallenge();
		request.getSession().setAttribute(CAPTCHA, code);
		OutputStream output = null;
		try {
			output = response.getOutputStream();
			ImageIO.write(captcha.getImage(), "png", output);
			
			output.flush();
		} catch (IOException e) {
		}finally{
			if(output != null){
				try {
					output.close();
				} catch (IOException e) {
				}
				
			}
		}
	}
	@GetMapping("/verification")
	public ResponseEntity<SimpleResult> verification(@ApiParam(required=false) String verification, HttpServletRequest request){
		SimpleResult vr=new SimpleResult();
		vr.setSuccess(false);
		String code = (String) request.getSession().getAttribute(CAPTCHA);
		if(code!=null&&verification!=null){
			if(code.equalsIgnoreCase(verification)){
				vr.setSuccess(true);
			}
		}
		return new ResponseEntity<SimpleResult>(vr, HttpStatus.OK);
	}
}
